﻿(function () {


    var urlDelete = "/bulletin/delete.do";
    var urlInfo = "/bulletin/content/info.do";
    var urlRead = "/bulletin/read.do";
    var urlSave = "/bulletin/save.do";
    var dataUrl = "/bulletin/list.do";
    var iWidth = document.documentElement.offsetWidth;//获取屏幕宽度-------------------------------------------
    var iHeight = document.documentElement.offsetHeight;//获取屏幕高度----------------------------
    var getIdArr = [];
    var getId;
    var Permission = true;
    var adopt = true;
    var modifyData = [];
    var getIndex;
    var dateTime;
    var limit=[];
    var exportTime=[];
    var getexportTime;
    var searchValue;
   
    $(function () {
        $_setDatagrid()
    })



    
    
    function $_setDatagrid(pageSize,pageNum,search) {
        
        var permit = true;
        var getColumns = [
            { field: 'type', title: '类型', width: iWidth*0.02, align: 'center',
                formatter: function (value, row, index) {
                    if(value == 1){
                        var str = "通知";
                    }
                    else if(value == 2){
                        var str = "公告";
                    }

                    return str;
                }
            },
            { field: 'title', title: '名称', width: iWidth*0.3, align: 'left',halign: 'center' },
            { field: 'resources', title: '单位来源', width: iWidth*0.04, align: 'center' },
            { field: 'mtime', title: '日期', width: iWidth*0.04, align: 'center' ,

                formatter: function (value, row, index) {
                    var myDate = new Date(value);
                    var result=myDate.getFullYear()+"年"+(myDate.getMonth()+1)+"月"+myDate.getDate()+'日'
                    return result;
                }
            },
            { field: 'editor', title: '发布人', width:  iWidth*0.04, align: 'center' },
            {field: 'operate', title: '操作', align: 'center', width:iWidth*0.03,
                formatter: function (value, row, index) {
                    var str = '<a href="#" name="opera" class="easyui-linkbutton" id='+"row"+row.bid+'>删除</a>';
                    return str;
                }
            },
        ];
        var dataList;
        var start;



        if(!pageSize&&!pageNum){
            if(search){
                dataList = {
                    page:1,
                    pageSize:20,
                    title:search
                }
                start = 0;
            }
            else {
                dataList = {
                    page:1,
                    pageSize:20,
                }
                start = 0;
            }


        }else {
            // dataList = {
            //     page:pageNum,
            //     pageSize:pageSize,
            // }
            // start = (pageNum-1) * pageSize;

            //-------------------------------------------------------修改处
            if (search) {
                dataList = {
                    page: pageNum,
                    pageSize: pageSize,
                    title:search
                }
                start = (pageNum - 1) * pageSize;
            }
            else {
                dataList = {
                    page: pageNum,
                    pageSize: pageSize,
                }
                start = (pageNum - 1) * pageSize;
            }
            //-------------------------------------------------------
        }




        $.get(dataUrl,dataList,function (json) {
            var obj = eval('(' + json + ')');
            var data = obj["data"]['results'];
            var total = obj["data"]['size'];

            var endLength = total%pageSize;
            var eLength;
            if(pageNum == Math.ceil(total/pageSize)){
                if(endLength!==0){
                    eLength = endLength;
                }
                else{
                    eLength = dataList.pageSize;
                }
            }
            else {
                eLength = dataList.pageSize;
            }


            $('#dataTab').datagrid({
                title: '管理',
                fitColumns: true,
                showFooter: true,
                fit: true,
                width:iWidth,
                height:iHeight,
                pagination:true,
                rownumbers:true,
                singleSelect:true,
                columns: [getColumns],
                pageSize: pageSize,
                pageNumber: pageNum,
                striped:true,
                data:data,
                toolbar:[{
                    //增加通知公告按钮---------------------------------------------------------------------------
                    id:"addBtn",
                    text:'增加',
                    iconCls:'icon-add',
                    width:100,
                    handler:function () {
                        var myDate = new Date();
                        dateTime = myDate.getTime();
                        var result=myDate.getDate()+'/'+(myDate.getMonth()+1)+"/"+myDate.getFullYear();
                        $_save('增加','','','',result,'','',"1",dateTime)
                    }
                    },'-',
                    {
                        //添加搜索---------------------------------------------------------------------------
                        id:'search'
                    }
                ],
                onClickRow:function (index,row) {
                    if(permit) {
                        for(var i=0;i<limit.length;i++){
                            if(limit[i]==row.bid){
                                return
                            }
                        }

                        limit.push(row.bid);
                        $_see(row.cid,row.bid,row.title,row.type,row.mtime,row.resources,row.editor)
                        getIdArr.push(row.bid)
                        adopt = true
                    }
                },
                onClickCell:function (index, field, value) {

                    if(field != "operate"){
                        permit = true;
                    }

                },
                onLoadSuccess:function() {
                    $("a[name='opera']").linkbutton({
                        text: '删除',
                        plain: true,
                        iconCls: 'icon-cancel',
                        width: iWidth * 0.054,
                        height: 25,
                        onClick:function () {
                            permit = false;
                            var that = this

                            var dataDeleteBid = {"bid":that.id.replace(/[a-zA-Z]/g,"")}
                                $.messager.confirm('确认','删除后不可恢复，你确定删除吗？',function(r){
                                    if (r){
                                        $.get(urlDelete,dataDeleteBid,function (dataDeleteResult) {
                                            var rows = $("#dataTab").datagrid("getRows");
                                            for(var i=0; i<rows.length; i++){
                                                if(that.id.replace(/[a-zA-Z]/g,"") == rows[i].bid){
                                                    $('#dataTab').datagrid('deleteRow',i);
                                                }
                                            }
                                            $_setDatagrid();
                                        })
                                    }

                            })
                        }
                    });
                    $('#search').textbox({
                        buttonText:'搜索',
                        iconAlign:'left',
                        width:200,
                        height:30,
                        onClickButton:function () {
                            if($('#search').textbox("getValue").replace(/(^\s*)|(\s*$)/g, "")==""){
                                $.messager.alert('确认','搜索不能为空');
                                return
                            }
                            searchValue = $('#search').textbox("getValue");
                            $_setDatagrid(undefined,undefined,$('#search').textbox("getValue"));
                        }
                    })
                }
            })

            var pager = $("#dataTab").datagrid("getPager");
            pager.pagination({
                total:total,
                pageList: [20,30,50,100,200,500,1000],
                pageSize:dataList.pageSize,
                pageNumber:dataList.page,
                beforePageText: '第',
                afterPageText: '页    共 ' + Math.ceil(total / dataList.pageSize) + ' 页',
                displayMsg: '当前显示 ' + (start + 1) + '-' + (start + eLength) + ' 条记录 共 ' + total + ' 条记录',
                onRefresh:function(pageNumber,pageSize){
                    searchValue = undefined;
                    $_setDatagrid();
                    // $_setDatagrid(pageSize,pageNumber)
                },
                onSelectPage:function (pageNo, pageSize) {
                    // $_setDatagrid(pageSize,pageNo)
                    if(searchValue==''||searchValue==undefined){
                        $_setDatagrid(pageSize,pageNo);
                    }
                    else {
                        $_setDatagrid(pageSize,pageNo,searchValue);
                        console.info(searchValue);
                    }
                }
            });

        })

    }



    function timestamp(url){
        var getTimestamp=new Date().getTime();
        if(url.indexOf("?")>-1){
            url=url+"&timestamp="+getTimestamp
        }else{
            url=url+"?timestamp="+getTimestamp
        }
        return url;
    }

    function getLocalTime(nS) {

        return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/,'');
    }

    function $_see(id,bid,title,type,mtime,resources,editor) {

        var mWidth = document.documentElement.offsetWidth;
        var mHeight = document.documentElement.offsetHeight;

        var dataCid = {"cid":id}

        $.get(urlInfo,dataCid,function(json) {

            var obj = eval('(' + json + ')');

            var data = obj["data"]
            var result = {};

                if (id == obj["data"].id) {
                    obj["data"].title = title;
                    obj["data"].type = type;
                    obj["data"].mtime = mtime;
                    obj["data"].resources = resources;
                    obj["data"].editor = editor;
                    result = obj["data"]
                }
            exportTime.push(mtime);
            modifyData.push(result);

            if (Permission) {

                $('#seeTabs').tabs({
                    border: false,
                    scrollDuration: 1,

                    onAdd:function () {



                        var readCid = {bid:bid}

                        $.get(urlRead,readCid,function(json) {

                        })
                    }
                    ,
                    onClose: function (title, index) {
                        var tab = $('#seeTabs').tabs('tabs');
                        var len = tab.length;
                        getIdArr.splice(index,1);
                        modifyData.splice(index,1);
                        limit.splice(index,1);
                        exportTime.splice(index,1);
                        console.info(limit);
                        if (len == 0) {
                            $('#seeView').dialog('close');
                        }
                    }
                })

            $('#seeView').dialog({
                width: mWidth * 0.8,
                height: mHeight-60,
                // noheader:true,
                title: "查看",
                buttons: [
                    {
                        id:"exportBtn",
                        text:'导出Word',
                        iconCls:'icon-word',
                        width:100,
                        handler:function () {
                            var tab = $('#seeTabs').tabs('getSelected');
                            var index = $('#seeTabs').tabs('getTabIndex',tab);
                            var getTab =  $('#seeTabs').tabs('getTab',index);
                            $('#'+getTab[0].childNodes[0].id).wordExport(modifyData[index].title);
                        }
                    },

                    {
                    text: '修改',
                    iconCls: 'icon-edit',
                    width: 100,
                    handler: function () {
                        var tab = $('#seeTabs').tabs('getSelected');
                        var index = $('#seeTabs').tabs('getTabIndex',tab);
                        getId = getIdArr[index];
                        getIndex = index;
                        getexportTime = exportTime[index];

                        var myDate = new Date();
                        dateTime = myDate.getTime();
                        var result=myDate.getDate()+'/'+(myDate.getMonth()+1)+"/"+myDate.getFullYear();
                        $_save('修改',getId,modifyData[getIndex].title,modifyData[getIndex].info,result,modifyData[getIndex].editor,modifyData[getIndex].resources,modifyData[getIndex].type,dateTime);
                    }
                }

                ],
                onOpen: function () {
                    $("a[name='opera']").linkbutton('disable');
                },
                onBeforeClose: function () {
                    //获取tabs的选项卡个数---------------------------------------------------------------------------
                    var tab = $('#seeTabs').tabs('tabs');
                    var len = tab.length;
                    //关闭所有选项---------------------------------------------------------------------------
                    for (var i = tab.length; i >= 0; i--) {
                        $("#seeTabs").tabs('close', i)
                    }
                    Permission = true;
                    $("a[name='opera']").linkbutton('enable');//关闭时启用删除按钮---------------------------------------------------------------------------
                    limit.length = 0;
                }
            })


                Permission = false
        }

            var myDate = new Date(mtime);
            var time=myDate.getFullYear()+"年"+(myDate.getMonth()+1)+"月"+myDate.getDate()+'日'

            $('#seeTabs') .tabs('add', {
                title:result.title,
                content:"<div id='export-content"+id+"'><h4 style='text-align: center; font-size: 25px; letter-spacing:1px; width: 60%; margin: 30px auto; padding-left:10px; padding-right:10px; word-wrap: break-word; word-break: normal; '>" + title + "</h4>" +

                "<div style=' margin: 0 auto; width: 75%;  padding: 10px;  font-size: 20px; text-indent:2em; min-height: 400px; letter-spacing:1px; word-wrap: break-word; word-break: normal;'>"

                + result.info +

                "</div>" +

                "<div style='width: 70%; margin: 0 auto;padding: 10px;'>"

                + "<span style='display: block;  line-height: 20px;  font-size: 20px; text-align: right; letter-spacing:1px;'>" + resources + ":" + editor + "</span>" +

                "<span style='display: block;  line-height: 20px;  font-size: 20px; text-align: right; margin-top: 10px; letter-spacing:1px; '>" + time + "</span>" +

                "</div></div></div>",
                closable: true,
                plain: true,
            })
        })
    }

    
    function $_save(titleType,bid,title,info,mtime,editor,resources,type,time) {

        document.getElementById("save").style.display = "block"
        var myDate = new Date();
        var result=myDate.getDate()+'/'+(myDate.getMonth()+1)+"/"+myDate.getFullYear()+" "+myDate.getHours()+":"+myDate.getMinutes()
        $("#date").textbox('disable');
        $("#save").dialog({
            resizable: false,
            closable: true,
            collapsible: false,
            maximizable:false,
            minimizable: false,
            title:titleType,
            modal:true,
            onOpen:function(){
                var iEditor_id = document.getElementById("editor_id");
                $("#editor_id").kindeditor({resizeType: 0});
                $('#title').textbox('setValue',title);
                $('#date').datebox('setValue',mtime);
                $('#resources').textbox('setValue',resources);
                $('#editor').textbox('setValue',editor);
                if(type==1){
                    $('#type').combobox('setValue','通知')
                }
                else {
                    $('#type').combobox('setValue','公告')
                }
                for(var i=0; i<document.getElementsByTagName("iframe").length; i++){
                    if(document.getElementsByTagName("iframe")[i].className == "ke-edit-iframe"){
                        document.getElementsByTagName("iframe")[i].contentWindow.document.body.innerHTML = info;
                    }
                }
            },
            buttons: [{
                text: '提交',
                iconCls: 'icon-ok',

                //点击提交按钮
                handler: function () {

                    var content;
                    for(var i=0; i<document.getElementsByTagName("iframe").length; i++){
                        if(document.getElementsByTagName("iframe")[i].className == "ke-edit-iframe"){
                            content =  document.getElementsByTagName("iframe")[i].contentWindow.document.body.innerHTML
                        }
                    }

                    var commitType;

                    if($('#type').combobox('getValue') == "通知"){
                        commitType = "1";
                    }
                    else if($('#type').combobox('getValue') == "公告"){
                        commitType = "2";
                    }
                    else {
                        commitType = $('#type').combobox('getValue');
                    }

                    var saveData;

                    if(titleType == "修改"){
                        saveData = {
                            bid:bid,
                            content:content,
                            type:commitType,
                            title:$('#title').textbox('getValue'),
                            resources:$('#resources').textbox('getValue'),
                            mtime:time,
                            // editor:$('#editor').textbox('getValue')
                        }
                    }
                    else {
                        saveData = {
                            content:content,
                            type:commitType,
                            title:$('#title').textbox('getValue'),
                            resources:$('#resources').textbox('getValue'),
                            mtime:myDate.getTime(),
                            // editor:$('#editor').textbox('getValue')
                        }
                    }

                    console.info(saveData)

                    $.post(urlSave,saveData,function(result){
                        for(var i in saveData){
                            if(i!==bid){
                                if((saveData[i]+"").replace(/(^\s*)|(\s*$)/g, "")==""){
                                    $.messager.alert('消息','必填项不能为空');
                                    return
                                }
                            }

                        }
                        if(saveData.bid){
                            $.messager.alert('消息','修改成功！若查看修改，请关闭重新打开或刷新');

                        }
                        else {
                            $.messager.alert('消息','添加成功！');
                        }
                        $_setDatagrid();
                        $('#save').dialog('close');
                    })
                }
            },
                {
                    text: '取消',
                    iconCls: 'icon-cancel',

                    //点击取消按钮
                    handler: function () {
                        $('#save').dialog('close');
                    }
                }


            ]
        })

        $(".panel-with-icon").addClass("title")
        $(".title").css({marginLeft:"0px"})
    }
})()